//
//  SCVinScanViewController.m
//  Shuaiche
//
//  Created by 党帅 on 2019/6/18.
//  Copyright © 2019 zzs. All rights reserved.
//

#import "SCVinScanViewController.h"
#import "SCVinCamera.h"
#import "SCOCR.h"
#import "UIImage+Resize.h"
#import "MBProgressHUD+Add.h"
#import "SCWeakTimer.h"
#import <Masonry.h>
#import "SCSysHelper.h"
@interface SCVinScanViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
//@property (nonatomic, strong) SCOCR *ocr;
@property (nonatomic, strong) SCVinCamera *camera;

@property (weak, nonatomic) IBOutlet UIView *videoView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *videoViewTop;
@property (weak, nonatomic) IBOutlet UIImageView *currentImageView;

@property(nonatomic, assign) BOOL imageFromLib;
@property (nonatomic, assign) BOOL isRecognizing;
@property (nonatomic, assign) BOOL shouldGenImage;
@property (nonatomic, strong) UIStackView *hud;
@property (nonatomic, strong) UIButton *torchButton;
@property (nonatomic, strong) UIButton *backButton;
@end

@implementation SCVinScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SC_RGB(34, 34, 34);
    _videoViewTop.constant = kSCNavigationHeight;

    [self createMaskView];
    [self updateTitleView];
}

- (void)updateTitleView {
//    UILabel *titleLabel = [[UILabel alloc] init];
//    titleLabel.text = @"VIN扫描";
//    titleLabel.textColor = [UIColor whiteColor];
//    titleLabel.font = SC_FONT_Bold(18);
//    self.navigationItem.titleView = titleLabel;
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"请先对准带有车架号的位置，然后点击下方拍摄按钮";
    label.textColor = [UIColor whiteColor];
    label.font = SC_FONT(16);
    label.textAlignment = 1;
    label.numberOfLines = 2;
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(150 + kSCNavigationHeight));
        make.left.equalTo(@10);
        make.right.equalTo(@(-10));
    }];
    
    _torchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_torchButton setImage:[UIImage imageNamed:@"vin_torch_off"] forState:0];
    [_torchButton setImage:[UIImage imageNamed:@"vin_torch_on"] forState:UIControlStateSelected];
    [_torchButton addTarget:self action:@selector(torchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_torchButton];
    [_torchButton mas_makeConstraints:^(MASConstraintMaker *make) {
      make.size.mas_equalTo(CGSizeMake(44, 44));
      make.right.mas_equalTo(-10);
      make.top.mas_equalTo(STATUSBAR_HEIGHT);
    }];
  
  _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [_backButton setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
  [_backButton addTarget:self action:@selector(backEvent) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_backButton];
  [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.mas_equalTo(CGSizeMake(60, 44));
    make.left.mas_equalTo(0);
    make.top.mas_equalTo(STATUSBAR_HEIGHT);
  }];
    
}

#pragma mark - backEvent
-(void)backEvent {
  [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    self.hideNavigationBar = YES;
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!_imageFromLib) {
        [self.camera start];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    self.hideNavigationBar = NO;
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [SCSysHelper changeStatusBarStyle:UIStatusBarStyleDefault];
    [_camera stop];
    _torchButton.selected = NO;
}

- (void)processOcrResult:(NSString *)vin {
    NSLog(@"识别结果：%@",vin);
    if (vin.length > 0) {
        [_camera stop];
        self.resultBlock(vin);
    } else {
        _isRecognizing = NO;
    }
}

- (BOOL)shouldGenerateImage {
    if (_shouldGenImage && !_isRecognizing) {
        _shouldGenImage = NO;
        return YES;
    }
    return NO;
}

- (void)processImage:(UIImage *)image {
        
//    _currentImageView.image = image;
    _isRecognizing = YES;
    self.hud.hidden = NO;
    [SCOCR aliOcrRecognizeImage:image completion:^(NSString *vin) {
        _hud.hidden = YES;
        [self processOcrResult:vin];
    }];
}

- (void)processImageFromLib:(UIImage *)image {
    self.hud.hidden = NO;
    [SCOCR aliOcrRecognizeImage:image completion:^(NSString *vin) {
        _hud.hidden = YES;
        if (vin.length) {
            if (self.resultBlock) {
                self.resultBlock(vin);
            }
        } else {
            [_camera start];
            [MBProgressHUD showPlainText:@"未识别到车架号，请重新选择图片"];
        }
    }];
}

- (void)torchButtonClick {
    _torchButton.selected = !_torchButton.isSelected;
    [_camera torchSwitch];
}

- (IBAction)selectImageFromLibrary:(UIButton *)sender {
    _imageFromLib = YES;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.navigationBar.translucent = NO;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}

- (IBAction)generateImageButtonClick:(UIButton *)sender {
    _shouldGenImage = YES;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    UIImage *image= [info objectForKey:UIImagePickerControllerOriginalImage];
    image = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds)) interpolationQuality:0.1];
    [self processImageFromLib:image];
  [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [_camera start];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)createMaskView {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.backgroundColor = [UIColor clearColor].CGColor;
    
    shapeLayer.frame = CGRectMake(0, 0, kSCScreenWidth, kSCScreenHeight - kSCNavigationHeight);
    [_videoView.layer addSublayer:shapeLayer];

    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, kSCScreenWidth, kSCScreenHeight - kSCNavigationHeight)];
    shapeLayer.fillRule = kCAFillRuleEvenOdd;
    shapeLayer.fillColor = SC_RGBA(0, 0, 0, 0.6).CGColor;
    
    // 视频展示层调整后的启示坐标
    CGFloat offsetY = (kSCScreenHeight - kSCNavigationHeight - kSCScreenWidth * 640/480.f) / 2.f;
    
    // y 为 需要抠图的起点
    CGFloat x = 15, y = offsetY + 195 - kSCNavigationHeight, h = 110, w = kSCScreenWidth - 2 *x;
    
    [bezierPath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(x, y, w, h)]];
    shapeLayer.path = bezierPath.CGPath;
    
    CGFloat cor_l = 15, cor_w = 2;
    h += cor_w;
    CAShapeLayer *cornerBorder = [CAShapeLayer layer];
    UIBezierPath *cornerPath = [UIBezierPath bezierPath];
    [cornerPath moveToPoint:CGPointMake(cor_l, 0)];
    [cornerPath addLineToPoint:CGPointMake(0, 0)];
    [cornerPath addLineToPoint:CGPointMake(0, cor_l)];
    
    [cornerPath moveToPoint:CGPointMake(0, h - cor_l)];
    [cornerPath addLineToPoint:CGPointMake(0, h)];
    [cornerPath addLineToPoint:CGPointMake(cor_l, h)];
    
    w += cor_w;
    [cornerPath moveToPoint:CGPointMake(w - cor_l, h)];
    [cornerPath addLineToPoint:CGPointMake(w, h)];
    [cornerPath addLineToPoint:CGPointMake(w, h - cor_l)];
    
    [cornerPath moveToPoint:CGPointMake(w, cor_l)];
    [cornerPath addLineToPoint:CGPointMake(w, 0)];
    [cornerPath addLineToPoint:CGPointMake(w - cor_l, 0)];
    
    x = x - cor_w/2;
    y = y - cor_w/2;
    cornerBorder.path = cornerPath.CGPath;
    cornerBorder.frame = CGRectMake(x, y, w, h);
    cornerBorder.strokeColor = SC_RGB(255, 219, 27).CGColor;
    cornerBorder.fillColor = [UIColor clearColor].CGColor;
    cornerBorder.lineWidth = cor_w;
    [shapeLayer addSublayer:cornerBorder];
}


- (SCVinCamera *)camera {
    if (!_camera) {
        _videoView.bounds = CGRectMake(0, 0, kSCScreenWidth, kSCScreenHeight - kSCNavigationHeight);
        _camera = [[SCVinCamera alloc] init];
        _camera.delegate = (id<SCVinCameraDelegate>)self;
        _camera.cropSize = CGSizeMake((kSCScreenWidth - 30)/kSCScreenWidth, 110.0 / (kSCScreenWidth * 1280/720.0));
        [_camera showInView:_videoView belowLayer:_videoView.layer.sublayers.lastObject];
    }
    return _camera;
}

- (UIStackView *)hud {
    if (!_hud) {
        _hud = [[UIStackView alloc] init];
        _hud.distribution = UIStackViewDistributionFill;
        _hud.axis = UILayoutConstraintAxisVertical;
        CGFloat y = (kSCScreenHeight - kSCNavigationHeight - kSCScreenWidth * 640/480.f) / 2.f;
        y = y + 260;
        _hud.bounds = CGRectMake(0, 0, 60, 65);
        _hud.center = CGPointMake(kSCScreenWidth/2, y);
        [self.view addSubview:_hud];
        
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [indicator startAnimating];
        [_hud addArrangedSubview:indicator];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = @"正在识别";
        label.font = SC_FONT(14);
        label.textColor = [UIColor whiteColor];
        [_hud addArrangedSubview:label];
    }
    return _hud;
}

@end
